import React, { Component } from 'react'
import './index.css'
import PropTypes from 'prop-types'

export default class Item extends Component {

    static propTypes = {
        updateTodo: PropTypes.func.isRequired
    }

    state = { mouse: false }
    handleMouse = (flag) => {
        return () => {
            this.setState({ mouse: flag })
        }
    }

    handleChange = (id) => {
        return (event) => {
            this.props.updateTodo(id, event.target.checked)
        }
    }

    handleDelete = (id) => {
        if (window.confirm('确定删除吗？')) {
            this.props.deleteTodo(id)        // 删除
        }
    }

    render() {
        const { id, name, done } = this.props;
        const { mouse } = this.state;
        return (
            <div>
                <li
                    style={{ backgroundColor: mouse ? '#ddd' : 'white' }}
                    onMouseLeave={this.handleMouse(false)}
                    onMouseEnter={this.handleMouse(true)
                    }>
                    <label>
                        <input type="checkbox" checked={done} onChange={this.handleChange(id)} />
                        <span>{name}</span>
                    </label>
                    <button onClick={() => this.handleDelete(id)} className="btn btn-danger" style={{ display: mouse ? 'block' : 'none' }}>删除</button>
                </li>
            </div>
        )
    }
}
